package com.dingyh.shopwebbackground.controller;


import com.dingyh.shopwebbackground.entity.Business;
import com.dingyh.shopwebbackground.entity.User;
import com.dingyh.shopwebbackground.service.BusinessService;
import com.dingyh.shopwebbackground.service.UserService;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-23
 */
@RestController
@CrossOrigin
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    BusinessService businessService;

    @Autowired
    UserService userService;

    /**
     * 通过id查找business
     * @param id
     * @return
     */
    @RequestMapping("/selectById")
    public CommonResult<Object> selectById(String id){
        Business business = businessService.selectByUserId(id);
        if(business != null) {
            return  new CommonResult<>(200,"",business);
        }else{
            return new CommonResult<>(500,"",null);
        }
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadImage")
    public  CommonResult<Object> uploadImage(@RequestPart("file") MultipartFile file){
        String path = "D:/GraduatioProject/shopWeb-background/src/main/webapp/upload_images/business/";
        String picName = System.currentTimeMillis() + ".jpg";
        File targetFile = new File(path, picName);//文件地址-文件名字
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
//            e.printStackTrace();
            return new CommonResult<>(500,"",null);
        }
        return  new CommonResult<>(200,"", picName);
    }

    /**
     * 商家注册
     * @param business
     * @return
     */
    @RequestMapping("registerBusiness")
    public CommonResult<Object> registerBusiness(Business business){
        if (business.getUserId().equals("6") ){
            int countMail = userService.getByMail(business.getMail());
            int countTel = userService.getByTel(business.getTel());
            if (countTel > 0 ) {
                return new CommonResult<>(500, "该手机号已存在");
            }
            if (countMail > 0) {
                return new CommonResult<>(500, "该邮箱号已存在");
            }
            String id = UUIDUtil.generator();
            Long time = System.currentTimeMillis();
            User user = User.builder()
                    .id(id)
                    .timeadd(time)
                    .nickname(business.getNickname())
                    .pwd(business.getPwd())
                    .avatar(business.getSaleLogo())
                    .mail(business.getMail())
                    .tel(business.getTel())
                    .money(BigDecimal.valueOf(0))
                    .disable("6")
                    .role("2")
                    .build();
            Business businessCurr = Business.builder()
                    .id(UUIDUtil.generator())
                    .nickname(business.getNickname())
                    .addressDetail(business.getAddressDetail())
                    .province(business.getProvince())
                    .city(business.getCity())
                    .area(business.getArea())
                    .certificate(business.getCertificate())
                    .intoPicture(business.getIntoPicture())
                    .saleLogo(business.getSaleLogo())
                    .tel(business.getTel())
                    .mail(business.getMail())
                    .pwd(business.getPwd())
                    .saleName(business.getSaleName())
                    .userId(id)
                    .timeAdd(time)
                    .build();
            if (userService.save(user) && businessService.save(businessCurr)) {
                return new CommonResult<>(200, "");
            } else {
                return new CommonResult<>(500, "");
            }
        }
        else {
            Business businessId = businessService.selectByUserId(business.getUserId());
            Long time = System.currentTimeMillis();
            User user = User.builder()
                    .id(businessId.getUserId())
                    .timeadd(time)
                    .nickname(business.getNickname())
                    .pwd(business.getPwd())
                    .avatar(business.getSaleLogo())
                    .mail(business.getMail())
                    .tel(business.getTel())
                    .money(BigDecimal.valueOf(0))
                    .disable("6")
                    .role("2")
                    .build();
            business.setTimeAdd(time);
            business.setId(businessId.getId());
            if (userService.updateById(user) && businessService.updateById(business)) {
                return new CommonResult<>(200, "");
            } else {
                return new CommonResult<>(500, "");
            }
        }
        //        bus.setId(id);
//        boolean flag = businessService.save(bus);
//        if(flag) {
//            List<BusinessImg> arr = new ArrayList<>();
//            List<String> intoPictureList = Arrays.asList(intoPictureArr.split(","));
//            for (String intoPicture : intoPictureList) {
//                arr.add(BusinessImg.builder().
//                        id(UUIDUtil.generator())
//                        .businessId(id)
//                        .type("2")
//                        .filePath(intoPicture).build());
//            }
//            List<String> nicePictureList = Arrays.asList(nicePictureArr.split(","));
//            for (String nicePicture : nicePictureList) {
//                arr.add(BusinessImg.builder().
//                        id(UUIDUtil.generator())
//                        .businessId(id)
//                        .type("3")
//                        .filePath(nicePicture).build());
//            }
//            businessImgService.saveBatch(arr);
//        }
    }

    /**
     *查找注册未审核的商家列表
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/getReviewBusinessList")
    public CommonResult<Object> getReviewBusinessList(@RequestParam(defaultValue = "1",required = true)int pageIndex,@RequestParam(defaultValue = "10",required = false)int pageSize){
        PageHelper.offsetPage((pageIndex - 1) * pageSize,pageSize);
        List<Business> businessList = businessService.getReviewBusinessList();
        businessList.forEach(business -> {
            User user = userService.selectById(business.getUserId(),"2");
            if (user.getDisable().equals("5")){
                business.setIsAgree("1");
            }else if (user.getDisable().equals("6")){
                business.setIsAgree("0");
            }else {
                business.setIsAgree("-1");
            }
        });
        PageInfo<Business> pageInfo = new PageInfo<>(businessList);
        return new CommonResult<>(200,"",pageInfo);
    }

    /**
     * 已审批完的表
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/getReviewedList")
    public CommonResult<Object> getReviewedList(@RequestParam(defaultValue = "1",required = true)int pageIndex,@RequestParam(defaultValue = "10",required = false)int pageSize){
        PageHelper.offsetPage((pageIndex - 1) * pageSize,pageSize);
        List<Business> businessList = businessService.getReviewedList();
        PageInfo<Business> pageInfo = new PageInfo<>(businessList);
        return new CommonResult<>(200,"",pageInfo);}
}

